/*
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
*/

class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode dummy(-1);
        dummy.next = head;
        ListNode *prev = &dummy, *cur = head;
        while (cur && cur->next) {
            if (cur->val == cur->next->val) {
                for (int num = cur->val; cur && cur->val == num;) {
                    ListNode *tmp = cur;
                    cur = cur->next;
                    delete tmp;
                }
                prev->next = cur;
            } else { prev = cur; cur = cur->next; }
        }
        return dummy.next;        
    }
};

#if 0
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        if (!head) return 0;
        ListNode *n_prev, *n;
        n_prev = n = head;
        while (n) {
            if (n->next && (n->next->val == n->val)) {
                /* detect a dup block */
                ListNode *n_end = n->next;
                while (n_end->next && (n_end->next->val == n->val)) {
                    n_end = n_end->next;
                }
                /* remove dup elems */
                if (n == head) {
                    head = n_end->next;
                    n_prev = n = head;
                } else {
                    n_prev->next = n_end->next;
                    n = n_end->next;
                }
            } else {
                /* move pointers */
                if (n_prev != n) {
                    n_prev = n_prev->next;
                }
                n = n_prev->next;
            }
        }
        return head;
    }
};
#endif
